<template>
  <van-popup v-model="toShow" position="right">
    <van-nav-bar class="nav_bar" title="选择提货点" left-text="取消" left-arrow @click-left="onClickBack"/>
    <van-cell-group>
      <van-cell :title="xiaoqu" :label="address" icon="location" style="background-color: lightblue;" />
    </van-cell-group>
    <van-cell-group v-if="shopList">
      <form action="/">
        <van-search v-model="searchKey" placeholder="请输入要搜索的小区名" show-action @search="onSearch" background="#00CC66">
          <div slot="action" @click="onSearch">搜索</div>
        </van-search>
      </form>
      <van-cell title="为您推荐附近的提货点" style="background-color: lightgoldenrodyellow;" />
      <van-cell v-for="shop in shopList" :key="shop.id" :title="shop.tXiaoqu" :label="shop.tShopname" :value="shop.distance + '公里'"
        clickable @click="onConfirm(shop.id)" />
     <is-empty v-if="shopList.length === 0">您附近还没有开通提货点哟，搜索试试</is-empty>
    </van-cell-group>
  </van-popup>
</template>

<script>
import {
  Picker,
  Search,
  NavBar
} from "vant";
import IsEmpty from "@/vue/components/is-empty/";
import wx from 'weixin-js-sdk';

import {
  NEAREST_SHOP
} from "@/api/shop";

export default {
  name: "pop-shop-sel",

  props: {
    show: Boolean,
  },

  data() {
    return {
      toShow: this.show,
      shopList: null,
      searchKey: '',
      longitude: 0,
      latitude: 0,
      xiaoqu: '定位中',
      address: '',
      inited: false
    }
  },

  watch: {
    show() {
      this.toShow = this.show;

      if (this.toShow && !this.inited) {
        this.initData();
      }
    },

    toShow() {
      this.$emit("onShow", this.toShow);
    }
  },

  mounted() {
    if (this.show) {
      this.initData();
    }
  },

  methods: {
    onCancel() {
      this.toShow = false;
    },

    onConfirm(shopId) {
      this.toShow = false;
      this.$emit("changeShop", shopId);
    },

    initData() {
      let v = this;
      v.inited = true;
      wx.ready(function () {
        //调用相关API
        wx.getLocation({
          type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (data) {
            v.longitude = data.longitude;
            v.latitude = data.latitude;
            v.initBMap().then(BMap => {
              let points = new BMap.Point(v.longitude, v.latitude);
              var convertor = new BMap.Convertor();
              convertor.translate([points], 1, 5, data => {
                if (data.status === 0) {
                  v.getNearestShop(data.points[0]);
                  let geoc = new BMap.Geocoder();
                  
                  geoc.getLocation(data.points[0], rs => {
                    console.log(rs);
                    if (rs.surroundingPois.length > 0) {
                      v.xiaoqu = rs.surroundingPois[0].title;
                      v.address = rs.surroundingPois[0].address;
                    }
                  });
                }
              })
            });
          },
          fail: function(data) {
            v.$toast.fail('定位失败');
          }
        });
      });
    },

    initBMap() {
      //console.log("初始化百度地图脚本...");
      const AK = "WGHV8O3FlG3LbAWy3MjaWxRKId0dQoCS";
      const BMap_URL = "https://api.map.baidu.com/api?v=2.0&ak=" + AK + "&s=1&callback=onBMapCallback";
      return new Promise((resolve, reject) => {
        // 如果已加载直接返回
        if (typeof BMap !== "undefined") {
          resolve(BMap);
          return true;
        }
        // 百度地图异步加载回调处理
        window.onBMapCallback = function () {
          console.log("百度地图脚本初始化成功...");
          resolve(BMap);
        };
        // 插入script脚本
        let scriptNode = document.createElement("script");
        scriptNode.setAttribute("type", "text/javascript");
        scriptNode.setAttribute("src", BMap_URL);
        document.body.appendChild(scriptNode);
      });
    },

    getNearestShop(point) {
      let v = this;
      v.$reqGet(NEAREST_SHOP, {
        longitude: point.lng,
        latitude: point.lat,
        limit: 10
      }).then(res => {
        console.log(res.data.data);
        v.$nextTick(() => {
          v.shopList = res.data.data;
          v.shopList.forEach(shop => {
            shop.distance = v.getDistance(point.lat, point.lng, shop.lat, shop.lng).toFixed(2);
          })
        });
      });
    },

    getDistance(lat1, lng1, lat2, lng2) {
      var radLat1 = lat1 * Math.PI / 180.0;
      var radLat2 = lat2 * Math.PI / 180.0;
      var a = radLat1 - radLat2;
      var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      return s;
    },

    onSearch() {

      this.$reqGet(NEAREST_SHOP, {
        teamName: this.searchKey,
        longitude: this.longitude,
        latitude: this.latitude,
        limit: 20
      }).then(res => {
        this.shopList = [];

        for (let i in res.data.data) {
          let shop = res.data.data[i];
          shop.distance = this.getDistance(this.latitude, this.longitude, shop.lat, shop.lng).toFixed(2);
          this.shopList[i] = shop;
        }
      });
    },

    onClickBack() {
      this.toShow = false;
    }
  },

  components: {
    [Picker.name]: Picker,
    [Search.name]: Search,
    [NavBar.name]: NavBar,
    [IsEmpty.name]: IsEmpty
  }
}
</script>

<style lang="scss" scoped>
.van-popup {
  &--right {
    width: 100%;
    height: 100%;
  }
}
.nav_bar {
  background-color: $green;
  color: white;
}
</style>
